package com.vcc.channel.base.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

public class RsaUtil {

    public static String md5Sign(String plainText, String key) {
        PrivateKey privateKey =
                SecureUtil.generatePrivateKey(AsymmetricAlgorithm.RSA.getValue(), Base64.decode(key));
        return sign(plainText,SignAlgorithm.MD5withRSA, privateKey);
    }

    public static String sha256Sign(String plainText, String key) {
        PrivateKey privateKey =
                SecureUtil.generatePrivateKey(AsymmetricAlgorithm.RSA.getValue(), Base64.decode(key));
        return sign(plainText,SignAlgorithm.SHA256withRSA, privateKey);
    }

    /**
     * 使用RSA签名
     *
     * @param plainText      待签名的明文
     * @param signAlgorithm  签名算法
     * @param privateKey     私钥
     * @return Base64编码的签名字符串
     */

    public static String sign(String plainText,SignAlgorithm signAlgorithm, PrivateKey privateKey) {
        Sign sign = SecureUtil.sign(signAlgorithm);
        sign.setPrivateKey(privateKey);
        return Base64.encode(sign.sign(plainText.getBytes(StandardCharsets.UTF_8)));
    }

}
